<?php
namespace zake\foundation\able\traits;

use zake\foundation\able\BeeAble;
use zake\foundation\able\reactor\ChannelAble;
use zake\foundation\able\reactor\ListenAble;
use zake\foundation\able\stream\RwBufferAble;
use zake\server\http\HttpListen;
use zake\server\zadb\ZaListen;

/**
 * Trait ConnectTrait
 * @package zake\foundation\able\traits
 *
 * @author liu.bin 2020-05-15 15:00
 */
trait ConnectTrait
{
    /**
     * @var int
     */
    protected $connectSecTime = 0;

    /**
     * 链接的微秒
     * 1秒(second) = 1000毫秒(millisecond) = 1000,000微秒(microsecond)
     * @var float
     */
    protected $connectMicroTime = 0;


    /**
     * @var null |ListenAble
     */
    protected $listener = null;

    /**
     * @var int
     */
    protected $connectId;


    // 事件监听 map [readBuffer,handShark]
    protected $_eventListenerMap = [];

    /**
     * 连接 编号
     * @return mixed
     *
     * @author liu.bin 2020-04-01 14:10
     */
    public function getConnectId()
    {
        return $this->connectId;
    }



    public function setConnectId($connectId)
    {
        $this->connectId = $connectId;
    }


    /**
     * 获取初始连接时间
     *
     * @author liu.bin 2020-03-28 21:17
     */
    public function getConnectTime($microTime=false)
    {
        return $microTime ? $this->connectMicroTime : $this->connectSecTime;
    }


    /**
     * 定义listener
     * @param ListenAble $listener
     *
     * @author liu.bin 2020-05-15 15:00
     */
    public function setListener(ListenAble $listener)
    {
        $this->listener = $listener;
    }


    /**
     * 获取listener
     * @return null|ListenAble|HttpListen|ZaListen
     *
     * @author liu.bin 2020-05-07 11:14
     */
    public function getListener()
    {
        return $this->listener;
    }


    /**
     * 获取与主进程通信channel
     * @return ChannelAble|BeeAble
     *
     * @author liu.bin 2020-05-15 17:37
     */
    public function getChannel()
    {
        return $this->getListener()->getChannel();
    }


    /**
     * todo 多机集群通信管道
     * @return RwBufferAble
     * @author liu.bin 2020-05-15 23:45
     */
    public function getCluster()
    {
        return null;
    }


    /**
     * 注册事件侦听
     * @param $eventType
     * @param \Closure $callBack
     *
     * @author liu.bin 2020-09-04 11:29
     */
    public function addEventListener($eventType,\Closure $callBack){
        if(!empty($eventType) && is_string($eventType) && !is_null($callBack) && $callBack instanceof \Closure){
            $this->_eventListenerMap[$eventType] = $callBack;
        }
    }


    /**
     * 触发事件
     *
     * @author liu.bin 2020-09-04 11:35
     */
    public function triggerEvent($eventType,$param=null){

        if(isset($this->_eventListenerMap[$eventType])){
            $this->_eventListenerMap[$eventType]($param);
        }

    }


}